package com.zll.dms.controller;

import com.zll.dms.constants.Constants;
import com.zll.dms.pojo.ResultData;
import com.zll.dms.pojo.param.RegisterParam;
import com.zll.dms.service.EmailService;
import com.zll.dms.service.AuthService;
import com.zll.dms.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("auth")
public class AuthController {

    @Autowired
    private EmailService emailService;

    @Autowired
    private AuthService authService;

    /**
     * 登录
     * @param name
     * @param password
     * @return
     */
    @PostMapping("login")
    public ResultData login(String name, String password) {
        if (StringUtils.isBlank(name)) {
            return ResultData.error("请输入用户名");
        }
        if (name.length()>20) {
            return ResultData.error("用户名长度不能超过20");
        }
        if (StringUtils.isBlank(password)) {
            return ResultData.error("请输入密码");
        }
        if (password.length()>20) {
            return ResultData.error("密码长度不能超过20");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        try {
            subject.login(token);
            return ResultData.success("登陆成功");
        } catch (Exception e) {
            return ResultData.error("账号或密码不正确");
        }
    }

    /**
     * 发送验证码
     * @param email
     * @return
     */
    @GetMapping("verificationcode")
    public ResultData sendCode(String email) {
        //邮箱验证
        if (!CommonUtils.checkEMail(email)) {
            return ResultData.error("邮箱格式不正确");
        }
        //发送生成验证码
        String code = RandomStringUtils.randomNumeric(6);
        //发送验证码
        String content = Constants.MAIL_CONTENT_CODE_PRE + code + Constants.MAIL_CONTENT_CODE_SUFF + Constants.MAIL_CONTENT_CODE_EFFECTIVE / 60000 + "分钟";
        emailService.sendEmail(email, Constants.MAIL_SUBJECT_CODE,content);
        //验证码和有效时间存进session
        Session session = SecurityUtils.getSubject().getSession();
        log.info("sessionId:{}",session.getId());
        Map<String, Object> codeMap = new HashMap<>(4);
        codeMap.put("code", code);
        codeMap.put("createTime", Calendar.getInstance().getTimeInMillis());
        session.setAttribute(email, codeMap);
        return ResultData.success("邮件已发送");
    }

    /**
     * 注册
     * @return
     */
    @PostMapping("register")
    public ResultData register(@Valid @RequestBody RegisterParam registerParam) {
        //验证验证码
        authService.checkCode(registerParam.getEmail(), registerParam.getCode());
        //持久化进数据库
        authService.registerUser(registerParam);
        return ResultData.success("注册成功，请前往登录");
    }

    /**
     * 退出登录
     * @return
     */
    @GetMapping("logout")
    public ResultData logout() {
        SecurityUtils.getSubject().logout();
        throw new UnauthenticatedException("当前用户不存在，请重新登陆");
    }

}
